//
//  SearchSurroundController.m
//  
//
//  Created by 郭明皓 on 15/11/2.
//
//

#import "SearchSurroundController.h"
#import "GMHSurroundModel.h"
#import "TuijianCell.h"

#import "GMHFindDetailViewController.h"
#import "GMHDataFiled.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import <AFNetworking.h>
#import "SearchController.h"
@interface SearchSurroundController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UIAlertViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, assign)int pageIndex;
@property (nonatomic, assign)BOOL isUpPull;
@property (nonatomic, retain)NSMutableArray *surroundArr;
@property (nonatomic, retain)UISearchBar *search;
@property (nonatomic, assign)NSInteger flag;

@end

@implementation SearchSurroundController

- (void)dealloc
{
    [_search release];
    [_surroundArr release];
    [_tableView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height + 40) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 100;
//    self.tableView.contentInset = UIEdgeInsetsMake(40, 0, 0, 0);//tableView 向下平移
    
    _search = [[UISearchBar alloc]initWithFrame:CGRectMake(20, 0, self.view.frame.size.width - 40, 40)];
    self.navigationItem.titleView = self.search;
    _search.placeholder = @"搜索目的地/景点/酒店等";
    self.search.barStyle = UIBarStyleDefault;
    [_search release];
    _search.delegate = self;
    
    
    [self UpPull];
    [self DownPull];
    
    self.surroundArr = [NSMutableArray array];
    
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    SearchController *city = [[SearchController alloc]init];
    [self.navigationController pushViewController:city animated:YES];
    [city release];

    
}

#pragma mark 上啦加载
- (void)UpPull
{
    __block SearchSurroundController *find = self;
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self.tableView.footer endRefreshing];
        self.pageIndex++;
        self.isUpPull = YES;
        [find create];
    }];
}
#pragma mark 下拉刷新
- (void)DownPull
{
    __block SearchSurroundController *find = self;
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageIndex = 1;
        self.isUpPull = NO;
        [find create];
    }];
    [self.tableView.header beginRefreshing];
}
#pragma mark 数据加载
- (void)create
{
    [GMHDataFiled isHaveFileDocument];
    [GMHDataFiled isHaveFileSurround];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *strurl = [NSString stringWithFormat:@"http://appapi.yaochufa.com/v2/Search/Search?p=%d&s=20&system=android&machineCode=ffffffff-9317-02f2-ffff-fffff60c2478&city=%%E5%%A4%%A7%%E8%%BF%%9E&minPrice=0&channel=xiaomimarket&sort=1&maxPrice=999999&version=4.3.1&keyWord=%@", _pageIndex, _cityName];
    
    NSString *cityStr = [strurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"ssssssssss%@", strurl);
    if (self.isUpPull == NO) {
        [self.surroundArr removeAllObjects];
    }
    [manager GET:cityStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSMutableArray *arry = [GMHSurroundModel baseModelArry:dic[@"data"][@"rows"]];
        [self.surroundArr addObjectsFromArray:arry];
        
        if (self.flag == self.surroundArr.count) {
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
        self.flag = self.surroundArr.count;
        if (_surroundArr.count > 0) {
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
        
        NSString *sendBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *CachesPath = [sendBoxPath stringByAppendingPathComponent:@"Travel/Surround/Title.plist"];
        [NSKeyedArchiver archiveRootObject:dic toFile:CachesPath];
//如果搜索没有结果
        if (self.surroundArr.count == 0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"没有结果" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            [alert release];
            [self.tableView.header endRefreshing];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"周边加载失败");
    }];
}
//alertVIew协议方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma  mark 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.surroundArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strs = @"tableView";
    TuijianCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
    if (!cell) {
        cell = [[TuijianCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strs];
    }
    
    GMHSurroundModel *model = [[GMHSurroundModel alloc]init];
    model = self.surroundArr[indexPath.row];
    
    [cell.leftimageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://cdn5.jinxidao.com/%@", model.appImageUrl]]placeholderImage:[UIImage imageNamed:@"travel.jpg"]];
    cell.title.text = model.appMainTitle;
    cell.describe.text = [NSString stringWithFormat:@"[%@]%@", model.city, model.appSubTitle];
    cell.money.text = [NSString stringWithFormat:@"￥%@", model.price];
    cell.normalMoney.text = [NSString stringWithFormat:@"￥%@", model.retailPrice];
    cell.sell.text = [NSString stringWithFormat:@"已售%@", model.saledCount];
    //高亮

    NSString *title = cell.title.text;
    NSMutableAttributedString *keyword1 = [[NSMutableAttributedString alloc]initWithString:title];
    NSRange keywordRange1 = [title rangeOfString:self.cityName];
    [keyword1 addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:keywordRange1];
    [cell.title setAttributedText:keyword1];

    
    NSString *cityName = cell.describe.text;
    NSMutableAttributedString *keyword = [[NSMutableAttributedString alloc]initWithString:cityName];
    NSRange keywordRange = [cityName rangeOfString:self.cityName];
    [keyword addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:keywordRange];
    [cell.describe setAttributedText:keyword];
    
    // 字体删除线
    NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@", model.retailPrice]];
    NSRange contentRange = {0.9,[content length]};
    [content addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleThick] range:contentRange];
    cell.normalMoney.attributedText = content;
    
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    self.tabBarController.tabBar.hidden = YES;
    GMHFindDetailViewController *detail = [[GMHFindDetailViewController alloc]init];
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
    GMHSurroundModel *find = self.surroundArr[indexPath.row];
    detail.productIds = find.productId;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
